package com.example.socialmediaplatform.controller;

import com.example.socialmediaplatform.model.DBFile;
import com.example.socialmediaplatform.dao.DBFileRepository;
import com.example.socialmediaplatform.payload.UploadFileResponse;
import com.example.socialmediaplatform.service.DBFileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

@RestController
@RequestMapping("/api/file")
public class FileUploadController {
    @Autowired
    private DBFileStorageService dbFileStorageService;
    @Autowired
    private DBFileRepository dbFileRepository;

    @PostMapping("/upload")
    public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file) {
        DBFile dbFile = dbFileStorageService.storeFile(file);
        String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
                .path("/api/downloadFile/")
                .path(dbFile.getId())
                .toUriString();
        dbFile.setFileURL(fileDownloadUri);
        dbFileRepository.save(dbFile);
        return ResponseEntity.ok(new UploadFileResponse(dbFile.getFileName(), fileDownloadUri, file.getContentType(), file.getSize()));
    }
} 
